import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.routers.banpick_router import banpick_router
from app.routers.common_router import common_router
from app.routers.game_router import game_router
from app.exception.cus_exception import TokenInvalidException, InvalidGameException, InvalidActionException
from db.mysql_part import get_mysql_engine
from contextlib import asynccontextmanager
from scripts.load_data import init_mysql_data, init_mongo_data
import asyncio
from utils.log_util import logger
import logging

@asynccontextmanager
async def lifespan(app: FastAPI):
    # await asyncio.gather(init_mysql_data(), init_mongo_data())
    yield
    await get_mysql_engine().dispose()

app = FastAPI(lifespan=lifespan)


app.include_router(banpick_router)
app.include_router(common_router)
app.include_router(game_router)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return "系别战"

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    try:
        response = await call_next(request)
        return response
    
    # 100001 房间不存在
    except TokenInvalidException as e:
        logger.error(f"TokenInvalidException：{e.message}")
        return JSONResponse(status_code=401, content={'code': 401, 'msg': e.message})
    except InvalidGameException as e:
        logger.error(f"{f'用户：{e.user_id}，' if e.user_id else ''}{f'对局：{e.game_id}，' if e.game_id else ''}InvalidGameException：{e.message}")
        return JSONResponse(status_code=400, content={'code': 100001, 'msg': e.message})
    except InvalidActionException as e:
        logger.error(f"{f'用户：{e.user_id}，' if e.user_id else ''}{f'对局：{e.game_id}，' if e.game_id else ''}InvalidActionException：{e.message}")
        return JSONResponse(status_code=400, content={'code': 100002, 'msg': e.message})


from utils.log_util import LOGGING_CONFIG
if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, log_config=LOGGING_CONFIG, access_log=False)
